# -*- coding: utf-8 -*-
# 第一行必须有，否则报中文字符非ascii码错误

import urllib.request
import json,time, sys,string,csv
print(sys.getdefaultencoding())

# ak需要在百度地图开放平台申请
ak = "Fy9pZXcEOYTTFSiZrQCHOLfhKXnLZR6g"

# 关键词
query = "景点" #充电桩
tag = "景点"# "充电站", "加油加气站"
page_size = 20
page_num = 0
# regions = ['徐汇区','长宁区','静安区','普陀区','虹口区','杨浦区','闵行区','宝山区','嘉定区','浦东新区','金山区','松江区','青浦区','奉贤区','崇明区']
regions = ['铜山区','泉山区','云龙区','贾汪区','鼓楼区']

queryResults = []

for region in regions:
    np = True
    a = []
    while np == True:
        # 使用百度提供的url拼接条件
        url = "https://api.map.baidu.com/place/v2/search?ak=" + str(ak) + "&output=json&query=" + str(
            urllib.parse.quote(query)) +"&tag=" + str(urllib.parse.quote(tag)) + "&page_size=" + str(page_size) + "&page_num=" + str(page_num) + "&region="+str(urllib.parse.quote(region))

        # 请求url读取，创建网页对象
        print(region,url)
        jsonf = urllib.request.urlopen(url)
        page_num = page_num + 1
        jsonfile = jsonf.read()

        # 判断查询翻页进程
        s = json.loads(jsonfile)
        total = int(s["total"])
        a.append(total)

        res = s["results"]
        if len(res) > 0:
            for r in res:
                queryResults.append([r['uid'],r['name'],r['location']['lng'],r['location']['lat'],r['address'],r['province'],r['city'],r['area'],r['detail']])

        max_page = int(a[0] / page_size) + 1
        # 防止并发过高，百度地图要求并发小于120
        time.sleep(1)

        if page_num >= max_page:
            np = False
            page_num = 0
            print("search complete")
            print("total: " + str(a[0]))
            print("")

# 写入csv

headers = ['uid','name','lng','lat','address','province','city','area','detail']

with open('test.csv','w', newline='') as f:
    f_csv = csv.writer(f)
    f_csv.writerow(headers)
    f_csv.writerows(queryResults)

print
"ALL DONE!"